﻿import { Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import { Observable}from 'rxjs/observable';
import { Subject} from 'rxjs/Subject';
import {Hero}from './hero';
import { HeroSearchServie}from './hero-search.service';

@Component({
    moduleId: module.id,
    selector: 'hero-search',
    templateUrl: 'hero-search.component.html',
    styleUrls: ['hero-search.component.css'],
    providers: [HeroSearchServie]
})
export class HeroSearchComponent implements OnInit {
    heroes: Observable<Hero[]>;
    private searchTerms = new Subject<string>();
    //生产者模式的观察者事件流。
    constructor(private heroSearchService: HeroSearchServie,
        private router: Router
    ) { }

    //
    search(term: string): void {
        /*每次按抬起插入一个term用于搜索。
        */
        //Push a search term into the 
        //observable stream.
        this.searchTerms.next(term);
    }
    ngOnInit(): void {
        this.heroes = this.searchTerms
            .debounceTime(300)//wait for 300ms pause in events
            .distinctUntilChanged()//ignore if next search term
        //is same as previous.
            //每隔300模式取出一次，有明显区别的term
            //执行：如果有term就搜索，没有就返回空数组。
            .switchMap(term => term ? this.heroSearchService
                .search(term)
                : Observable.of<Hero[]>([]))
            .catch(error => {//angular2内置catch委托
                //带入实际行为的表达式函数。
                console.log(error);
                return Observable.of<Hero[]>([]);
            });
    }
    gotoDetail(hero: Hero): void {
        let link = ['/detail', hero.id];
        this.router.navigate(link);
    }
}